<?php
/**
 * Created by PhpStorm.
 * User: daimin
 * Date: 15/7/22
 * Time: 下午6:31
 */

namespace common\services\common;

use common\services\BaseService;
use common\entities\common\MyscrmFunctionupgradeEntity;
use common\entities\common\MyscrmPackageEntity;
use common\repositories\common\MyscrmAuthorizeRepository;
use common\repositories\common\MyscrmContractRepository;
use common\repositories\common\MyscrmApplicationRepository;
use common\repositories\common\MyscrmFunctionupgradeRepository;
use common\repositories\common\MyscrmOrganizationRepository;
use common\repositories\common\MyscrmPackageRepository;
use yii\helpers\ArrayHelper;

/**
 * 授权相关的服务接口类
 * Class MyscrmAuthorizeService
 * @package common\services\common
 */
class MyscrmAuthorizeService extends BaseService {

    private $_packageRepository = null;
    private $_organizationRepository = null;
    private $_myscrmApplicationRepository;
    private $_contractRepository;
    private $_myscrmAuthorizeRepository;
    private $_myscrmFunctionupgradeRepository;

    public function __construct(MyscrmPackageRepository $packageRepository,
                                MyscrmOrganizationRepository $organizationRepository,
                                MyscrmApplicationRepository $myscrmApplicationRepository,
                                MyscrmContractRepository $contractRepository,
                                MyscrmAuthorizeRepository $myscrmAuthorizeRepository,
                                MyscrmFunctionupgradeRepository $myscrmFunctionupgradeRepository
    ){
        $this->_packageRepository = $packageRepository;
        $this->_organizationRepository = $organizationRepository;
        $this->_myscrmApplicationRepository = $myscrmApplicationRepository;
        $this->_contractRepository = $contractRepository;
        $this->_myscrmAuthorizeRepository = $myscrmAuthorizeRepository;
        $this->_myscrmFunctionupgradeRepository = $myscrmFunctionupgradeRepository;
        parent::__construct();
    }

    /**
     * 拿到租户的所有授权的app
     * @param $orgName
     * @param bool $doFilter 是否执行过滤
     * @return static[]
     * @throws \Exception
     */
    public function getAuthorizedAppsByOrgName($orgName, $doFilter=true)
    {
        if (empty($orgName)) {
            throw new \Exception("orgName不能为空");
        }
        $orgId = $this->_organizationRepository->getOrgId($orgName);
        if(empty($orgId)){
            throw new \Exception("指定的商户不存在");
        }
        return $this->_myscrmAuthorizeRepository->getAuthorizeAppsByOrgId($orgId, $doFilter);
    }

    /**
     * 根据app的授权码得到详情
     * @param $orgName
     * @param $authCode
     * @param bool $doFilter  表示是否过滤掉已废弃的合同，授权数为0的合同，合同数为0的应用
     * @return array|null
     * @throws \Exception
     */
    public function getAuthorizedAppByCode($orgName, $authCode){
        if (empty($orgName)) {
            throw new \Exception("租户企业号不能为空");
        }
        if (empty($authCode)) {
            throw new \Exception("应用授权码不能为空");
        }
        $orgId = $this->_organizationRepository->getOrgId($orgName);
        if(empty($orgId)){
            throw new \Exception("指定的商户不存在");
        }
        return $this->_myscrmAuthorizeRepository->getAuthorizeAppByAppUniqueName($orgId, $authCode);
    }

    /**
     * 根据packageId获取其详情及合同列表
     * @param $orgName
     * @param $packageId
     * @return array
     * @throws \Exception
     */
    public function getAuthorizedPackageById($orgName, $packageId){
        if (empty($orgName)) {
            throw new \Exception("租户企业号不能为空");
        }
        if (empty($packageId)) {
            throw new \Exception("套餐包Id不能为空");
        }

        $orgId = $this->_organizationRepository->getOrgId($orgName);
        if(empty($orgId)){
            throw new \Exception("指定的商户不存在");
        }

        return $this->_contractRepository->getAuthorizedPackageById($orgId, $packageId);
    }


    /**
     * 获取租户的所有package详情及合同列表
     * @param $orgName
     * @return array
     * @throws \Exception
     */
    public function getAuthorizedPackagesAndContractsByOrgName($orgName){
        if (empty($orgName)) {
            throw new \Exception("租户企业号不能为空");
        }

        $orgId = $this->_organizationRepository->getOrgId($orgName);
        if(empty($orgId)){
            throw new \Exception("指定的商户不存在");
        }

        return $this->_contractRepository->getAuthorizedPackagesAndContractsByOrgId($orgId);
    }


    /**
     * 拿到租户的所有授权的package
     * @param $orgName
     * @return static[]
     * @throws \Exception
     */
    public function getAuthorizedPackagesByOrgName($orgName)
    {
        if (empty($orgName)) {
            throw new \Exception("orgName不能为空");
        }
        $orgId = $this->_organizationRepository->getOrgId($orgName);

        if(empty($orgId)){
            throw new \Exception("指定的商户不存在");
        }
        return $this->_myscrmAuthorizeRepository->getAuthorizePackagesByOrgId($orgId);
    }

    /**
     * 返回所有的package无论其是否授权
     * @param $orgName
     * @return static[]
     * @throws \Exception
     */
    public function getAuthorizedInfoByOrgName($orgName){
        if (empty($orgName)) {
            throw new \Exception("orgName不能为空");
        }
        $orgId = $this->_organizationRepository->getOrgId($orgName);

        if(empty($orgId)){
            throw new \Exception("指定的商户不存在");
        }
        $orgId = $this->_organizationRepository->getOrgId($orgName);
        $applicationList = $this->_myscrmApplicationRepository->getAll();
        $authList = $this->_myscrmAuthorizeRepository->getAuthorizeListByOrgId($orgId);
        $authUsedList = $this->_myscrmAuthorizeRepository->getUsedAuthorizeNum($orgName);
        return $this->formatAuthList($applicationList,$authList, $authUsedList);
    }

    /**
     * 不进行curl远程获取，所以没有used_num
     * @param $orgName
     * @return static[]
     * @throws \Exception
     */
    public function getAuthorizedPackagesByOrgNameNoCurl($orgName){
        if (empty($orgName)) {
            throw new \Exception("orgName不能为空");
        }
        $orgId = $this->_organizationRepository->getOrgId($orgName);

        if(empty($orgId)){
            throw new \Exception("指定的商户不存在");
        }
        return $this->_myscrmAuthorizeRepository->getAuthorizePackagesByOrgIdNoCurl($orgId);
    }

    /**
     * 获取老租户的应用列表
     * @param $orgName
     * @return static[]
     * @throws \Exception
     */
    public function getOldOrgPackagesByOrgName($orgName){
        if (empty($orgName)) {
            throw new \Exception("orgName不能为空");
        }
        $orgId = $this->_organizationRepository->getOrgId($orgName);

        if(empty($orgId)){
            throw new \Exception("指定的商户不存在");
        }
        return $this->_myscrmAuthorizeRepository->getOldOrgPackagesByOrgName();
    }

    /**
     * 拿到已授权数
     */
    function getUsedAuthorizeNum($orgcode){
        return MyscrmAuthorizeRepository::getUsedAuthorizeNum($orgcode);
    }

    /**
     * 查询指定的商户是否购买掌上售楼处
     * @param $orgName string 租户名称
     * @return bool
     * @throws \Exception
     */
    public function isBuyZsslc($orgName){
        if (empty($orgName)) {
            throw new \Exception("orgName不能为空");
        }
        $orgId = $this->_organizationRepository->getOrgId($orgName);
        if(empty($orgId)){
            throw new \Exception("商户不存在");
        }
        $pkg = $this->_packageRepository->getPackageByUniqueName(MyscrmPackageEntity::ZSSLC);
        if(empty($pkg)){
            throw new \Exception("没有掌上售楼处");
        }

        $zsslcObj = $this->_packageRepository->getPackageByOrgIdAndPkgId($orgId, $pkg['id']);
        if(empty($zsslcObj)){
            return false;
        }
        return true;
    }

    /**
     * 获取合同的总授权数
     * @param $orgName
     * @param $contractId
     * @return int
     * @throws \Exception
     */
    public function getContactTotalNum($orgName, $contractId){
        if (empty($orgName)) {
            throw new \Exception("租户企业号不能为空");
        }
        $orgId = $this->_organizationRepository->getOrgId($orgName);
        if(empty($orgId)){
            throw new \Exception("商户不存在");
        }
        if(empty($contractId)){
            throw new \Exception("合同ID不能为空");
        }

        $contract = $this->_contractRepository->getContractById($contractId);
        if(empty($contract) || $contract['Status'] != 1){
            throw new \Exception("不存在的合同或已作废");
        }

        return $this->_contractRepository->getContractTotalNum($orgId, $contractId);
    }

    /**
     * 根据一个授权ID获取其套餐包下所有的兄弟app的授权id
     * @param $orgName
     * @param $authorizeId
     * @return array
     * @throws \Exception
     */
    public function getAuthorizePackageAppBrothersAuthorId($orgName, $authorizeId){
        if (empty($orgName)) {
            throw new \Exception("租户企业号不能为空");
        }
        $orgId = $this->_organizationRepository->getOrgId($orgName);
        if(empty($orgId)){
            throw new \Exception("商户不存在");
        }

        return $this->_myscrmAuthorizeRepository->getAuthorizePackageAppBrothersAuthorId($orgId, $authorizeId);
    }

    /**
     * 拿到授权的总数
     * @param $authorizeId
     * @throws \Exception
     * @return int
     */
    public function getAuthorizeTotalNum($authorizeId){
        if(empty($authorizeId)){
            throw new \Exception("授权表ID不能为空");
        }

        return $this->_myscrmAuthorizeRepository->getAuthorizeTotalNum($authorizeId);

    }

    /**
     * 判断当前版本是否是MVP810版本
     * @param $orgName string 租户名称
     * @return bool
     * @throws \Exception
     */
    public function IsMvp810($orgName){
        if (empty($orgName)) {
            throw new \Exception("租户企业号不能为空");
        }
        $orgId = $this->_organizationRepository->getOrgId($orgName);
        if(empty($orgId)){
            throw new \Exception("商户不存在");
        }
        return MyscrmFunctionupgradeEntity::checkIs810Version($orgId);
    }

    public function getProjectBindAppNum($orgName){
        if (empty($orgName)) {
            throw new \Exception("租户企业号不能为空");
        }
        $orgId = $this->_organizationRepository->getOrgId($orgName);
        if(empty($orgId)){
            throw new \Exception("商户不存在");
        }

        return MyscrmAuthorizeRepository::getProjectBindAppNum($orgId, true);
    }

    /**
     * 获取指定租户的授权ID对应的绑定项目ID列表
     * @param $orgName
     * @return bool|int
     * @throws \Exception
     */
    public function getProjectIds($orgName){
        if (empty($orgName)) {
            throw new \Exception("租户企业号不能为空");
        }
        $orgId = $this->_organizationRepository->getOrgId($orgName);
        if(empty($orgId)){
            throw new \Exception("商户不存在");
        }

        return MyscrmAuthorizeRepository::getProjectIds($orgId, true);
    }

    public function getAllApplications()
    {
        $applicationList = $this->_myscrmApplicationRepository->getAll();
        return $this->formatApplicationList($applicationList);
    }

    /**
     * @param $applicationList \common\entities\common\MyscrmApplicationEntity[]
     * @param $authList \common\entities\common\MyscrmOrganizationToAuthorizeEntity[]
     * @param $authUsedList array [[AuthorizeId=>count],...]
     * @return array [应用名称 =>[应用内容],...]
     */
    private function formatAuthList($applicationList, $authList, $authUsedList)
    {
        /** @var \common\entities\common\MyscrmApplicationEntity[] $applicationIndexByIdList */
        $applicationIndexByIdList = ArrayHelper::index($applicationList, 'ApplicationId');
        $result = [];
        foreach ($authList as $auth) {
            $appName = $applicationIndexByIdList[$auth->ApplicationId]->FriendlyName;
            $authUsedCount = isset($authUsedList[$auth->Id]) ? $authUsedList[$auth->Id] : 0;
            if (!isset($result[$appName])) {

                $authArray = [
                    'id' => $auth->Id,
                    'friendly_name' => $appName,
                    'unique_name' => $applicationIndexByIdList[$auth->ApplicationId]->UniqueName,
                    'total_num' => $auth->TotalNum,
                    'used_num' => $authUsedCount,
                ];
                $result[$appName] = $authArray;
            }else{
                $result[$appName]['total_num'] += $auth->TotalNum;
                $result[$appName]['used_num'] += $authUsedCount;
            }
        }
        return $result;
    }

    /**
     * @param $applicationList array|\common\entities\common\MyscrmApplicationEntity[]
     * @return array
     */
    private function formatApplicationList($applicationList)
    {
        $result = [];
        foreach($applicationList as $application){
            $applicationArray = [
                'id' => $application->ApplicationId,
                'friendly_name' => $application->FriendlyName,
                'unique_name' => $application->UniqueName,
            ];
            $result[] = $applicationArray;
        }
        return $result;
    }

}
